package com.java.frontweb.intercepters;


import com.java.base.utils.CookieUtils;
import com.java.frontweb.pojo.User;
import com.java.frontweb.service.UserService;
import com.java.frontweb.thred.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName UserLoginHandlerInterceptor
 * @Description 用户未登录进入订单页拦截器
 * @Author Trigger Wu
 * @Date 2018/9/2219:44
 * @Version 1.0
 **/
@Component
public class UserLoginHandlerInterceptor implements HandlerInterceptor {

    public   static final  String COOKIE_NAME = "CQZG_TOKEN";

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = CookieUtils.getCookieValue(request,COOKIE_NAME);
        String loginUrl = userService.CQZG_SSO_URL+"/rest/service/user/login";
        //防止线程错误,用户信息丢失
        UserThreadLocal.set(null);
        if(StringUtils.isEmpty(token)){
            //未登录状态，强制跳转登录
            response.sendRedirect("Http://sso.cqzg.com/rest/service/user/login");
            return false;
        }
        User user = userService.queryByToken(token);
        if(null == user){
            //没有用户信息,跳转登录
            response.sendRedirect(loginUrl);
            return  false;
        }
        //将user对象放入同一线程中
        UserThreadLocal.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
